package com.ruoyi.business.service.impl;

import java.util.*;

import com.ruoyi.business.domain.ShopVerification;
import com.ruoyi.business.domain.vo.AggregatedOrder;
import com.ruoyi.business.service.IShopVerificationService;
import com.ruoyi.business.uitls.OrderNumber;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteCodeImageService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.model.LoginUser;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.OrdersMapper;
import com.ruoyi.business.domain.Orders;
import com.ruoyi.business.service.IOrdersService;

import javax.annotation.Resource;

/**
 * 店铺订单管理Service业务层处理
 *
 * @author xiao
 * @date 2024-09-11
 */
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private RemoteCodeImageService remoteCodeImageService;

    @Resource
    private RemoteFileService remoteFileService;
    @Resource
    private ElasticsearchRestTemplate restTemplate;
    @Resource
    private IShopVerificationService shopVerificationService;


    /**
     * 查询店铺订单管理
     *
     * @param id 店铺订单管理主键
     * @return 店铺订单管理
     */
    @Override
    public Orders selectOrdersById(Long id) {
        return ordersMapper.selectOrdersById(id);
    }

    /**
     * 查询店铺订单管理列表
     *
     * @param orders 店铺订单管理
     * @return 店铺订单管理
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
//        商户可查看的
        if (roles.contains("business") && !SecurityUtils.isAdmin(loginUser.getUserid())) {
            String username = loginUser.getSysUser().getUserName();

            ShopVerification shopVerification = new ShopVerification();
            shopVerification.setMobile(username);
//            根据系统用户表的username 查询获取 店铺认证表的 店铺id
            List<ShopVerification> shopVerifications = shopVerificationService.selectShopVerificationList(shopVerification);
            List<Long> mIds = new ArrayList<>();
            shopVerifications.forEach(shopVerification1 -> {
                Long mid = shopVerification1.getMId();
                System.out.println(shopVerification1.getMId());
                mIds.add(mid);
            });
            System.out.println("mIds:" + mIds);
            Long mid = mIds.get(0);
            System.out.println("mid.get[0]:" + mid);
//            List<Orders> ordersList = selectAllByMid(mid);
            orders.setMId(mid);
            List<Orders> ordersList = ordersMapper.selectOrdersList(orders);
            return ordersList;
        }
//      管理员可查看的
        return ordersMapper.selectOrdersList(orders);
    }


    // 使用es 根据服务类型聚合、度量
    @Override
    public List<AggregatedOrder> selectAllByType(Orders orders) {
        // 基于Orders类 生成一个可以操作es数据的对象：目前还没有请求es
        IndexOperations indexOps = restTemplate.indexOps(Orders.class);
        // 判断Orders对应的索引库是否存在：会请求es
        boolean exists = indexOps.exists();
        System.out.println("判断Orders对应的索引库是否存在：" + exists);
        if (!exists) {
            //索引库不存在：创建索引库
            indexOps.create();
            //在内存中创建映射
            Document document = indexOps.createMapping();
            //将映射更新到es的索引库中
            indexOps.putMapping(document);
        }

        // 查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 设置查询类型：match、term、fuzzy、range...
        queryBuilder.withQuery(QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("m_id", orders.getMId().toString()))
                .must(QueryBuilders.termQuery("pay_time",orders.getPayTime())));

//        queryBuilder.withQuery(QueryBuilders.termQuery("m_id", orders.getMId().toString())
//                .);

        queryBuilder.addAggregation(AggregationBuilders.terms("typeAggs").field("service_type_id")
                .subAggregation(AggregationBuilders.sum("sum_price")
                        .field("price"))
        );

        // 执行查询
        SearchHits<AggregatedOrder> searchHits = restTemplate.search(queryBuilder.build(), AggregatedOrder.class, IndexCoordinates.of("orders"));

        //获取聚合结果：使用第一层聚合的桶名作为键  聚合结果作为值存到map中
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        ParsedLongTerms typeAggs = aggregations.get("typeAggs");//获取第一层聚合的结果对象
        System.out.println("聚合结果：" + typeAggs + " , " + typeAggs.getClass());

        List<AggregatedOrder> result = new ArrayList<>();
        for (Terms.Bucket bucket : typeAggs.getBuckets()) {
            ParsedSum sumAggs = (ParsedSum) bucket.getAggregations().get("sum_price");
            Long serviceTypeId = (Long) bucket.getKey();
            Long ordersNum = (Long) bucket.getDocCount();
            Float value = (float) sumAggs.getValue();
            result.add(new AggregatedOrder(serviceTypeId, ordersNum,value));
        }
        System.out.println("result为:" + result);
        return result;


//        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(), Orders.class, IndexCoordinates.of("orders"));
//        List<Orders> ordersList = new ArrayList<>();
//        // 处理结果
//        System.out.println("处理结果："+searchHits.getSearchHits());
//        searchHits.getSearchHits().forEach(hit -> {
//            ordersList.add(hit.getContent());
//        });
//        System.out.println("当前登录商户订单ordersList:"+ordersList);
//        return ordersList;
    }



    /**
     * 新增店铺订单管理
     *
     * @param orders 店铺订单管理
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) throws Exception {
//        生成核销码
        UUID uuid = UUID.randomUUID();
        orders.setVerificationCode(uuid.toString());
        System.out.println("核销码：" + uuid.toString());
        System.out.println("新增的对象：" + orders.toString());
//        生成订单编号
        Long num = OrderNumber.generateOrderNumber();
        System.out.println("订单号：" + num);
        orders.setId(num);

//        生成核销二维码 ****
//        String text = "我是二维码的内容"; // 二维码内容
//        int width = 200; // 二维码图片宽度
//        int height = 200; // 二维码图片高度
//        String format = "jpg";// 二维码的图片格式
//
//        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
//        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
//
//        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建MultipartFile    ****
//        MultipartFile multipartFile = new MockMultipartFile(
//                "file", // 参数名
//                fileName, // 文件名
//                MediaType.IMAGE_JPEG_VALUE, // 内容类型
//                imageData // 文件内容
//        );
//        R<SysFile> result = remoteFileService.upload(multipartFile);
        // 处理上传结果
//        System.out.println("上传结果: " + result);

        // 生成二维码        ****
//        File outputFile = new File("g:" + File.separator + orders.getVerificationCode()+".jpg");
//        remoteFileService.upload()
//        Test.writeToFile(bitMatrix, format, outputFile);
//        System.out.println("二维码生成");
//        orders.setVerificationImg();

        return ordersMapper.insertOrders(orders);
    }

    /**
     * 修改店铺订单管理
     *
     * @param orders 店铺订单管理
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除店铺订单管理
     *
     * @param ids 需要删除的店铺订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByIds(Long[] ids) {
        return ordersMapper.deleteOrdersByIds(ids);
    }

    /**
     * 删除店铺订单管理信息
     *
     * @param id 店铺订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrdersById(Long id) {
        return ordersMapper.deleteOrdersById(id);
    }
}
